package com.gframework.boot.mvc.controller.protocal.basic;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import com.gframework.boot.mvc.controller.protocal.RestResponseHandler;

/**
 * 默认的异常拦截器
 * 
 * @since 2.0.0
 * @author Ghwolf
 */
@RestControllerAdvice
public class GFrameworkControllerAdvice {

	/**
	 * 前后端统一格式aop代理对象
	 */
	@Autowired
	private RestResponseHandler restResponseHandler;

	/**
	 * 404 not found 异常处理
	 */
	@ExceptionHandler(NoHandlerFoundException.class)
	@ResponseBody
	public Object noHandleFoundException(HttpServletRequest request, HttpServletResponse response, Throwable e) {
		return restResponseHandler.handleNoHandlerFoundException(request, response);
	}
	
	/**
	 * JSR 异常处理
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseBody
	public Object methodArgumentNotValidException(HttpServletRequest request, HttpServletResponse response, Throwable e) {
		MethodArgumentNotValidException me = (MethodArgumentNotValidException) e;
		return restResponseHandler.handleMethodArgumentNotValidException(me,request,response);
	}
	
	/**
	 * JSR 异常处理
	 */
	@ExceptionHandler(BindException.class)
	@ResponseBody
	public Object methodBindException(HttpServletRequest request, HttpServletResponse response, Throwable e) {
		BindException me = (BindException) e;
		return restResponseHandler.handleBindException(me,request,response);
	}

	/**
	 * 默认异常处理
	 */
	@ExceptionHandler(Throwable.class)
	@ResponseBody
	public Object handleException(HttpServletRequest request, HttpServletResponse response, Throwable e) {
		return restResponseHandler.handleResult(e, request, response);
	}
}
